import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import FileSystemModel
import SystemIconProvider

Rectangle {
    id: diskPanel
    color: "#f5f5f5"
    border.color: "#d0d0d0"
    border.width: 1

    // 属性
    property string selectedFolderId: ""
    property var expandedItems: ({})
    property string pendingOpenFileId: ""  // 待打开的文件ID

    // 原有的主内容区域
    RowLayout {
        anchors.fill: parent
        spacing: 0

        // 左侧面板 - 目录树
        Rectangle {
            Layout.fillHeight: true
            Layout.preferredWidth: 350
            Layout.minimumWidth: 250
            color: "#f5f5f5"
            border.color: "#d0d0d0"
            border.width: 1

            ColumnLayout {
                anchors.fill: parent
                anchors.margins: 10
                spacing: 10

                // 地址栏和导航
                ColumnLayout {
                    Layout.fillWidth: true
                    spacing: 5

                    // 面包屑导航
                    RowLayout {
                        Layout.fillWidth: true
                        spacing: 5

                        Text {
                            text: "当前位置:"
                            font.pixelSize: 10
                            color: "#666666"
                        }

                        Text {
                            Layout.fillWidth: true
                            text: fileSystemModel.currentPath
                            font.pixelSize: 10
                            color: "#666666"
                            elide: Text.ElideLeft
                        }
                    }
                }

                // 目录列表
                ScrollView {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    clip: true

                    ListView {
                        id: directoryList
                        model: {
                            var result = [];
                            var currentPath = fileSystemModel.currentPath;
                            console.log("buildTree - 开始构建树形结构，当前路径:", currentPath);

                            // 递归函数构建树形结构
                            function buildTree(path, level, expandedItems) {
                                console.log("buildTree - 处理路径:", path, "级别:", level);
                                var contents = fileSystemModel.getDirectoryContents(path, false); // 只获取文件夹，不包含文件
                                console.log("buildTree - 获取到内容数量:", contents.length, "内容:", contents);

                                for (var i = 0; i < contents.length; i++) {
                                    // 数据库模式：contents[i] 是文件夹ID，所有内容都是文件夹
                                    console.log("buildTree - 发现目录ID:", contents[i]);

                                    var item = {
                                        id: contents[i], // 文件夹ID
                                        name: fileSystemModel.getFolderName(contents[i]), // 根据ID获取真实名称
                                        level: level,
                                        expanded: expandedItems[contents[i]] === true,
                                        hasChildren: false
                                    };

                                    // 检查是否有子目录
                                    var subContents = fileSystemModel.getDirectChildren(contents[i]);
                                    console.log("buildTree - 检查子目录:", contents[i], "子目录数量:", subContents.length);
                                    item.hasChildren = subContents.length > 0;

                                    console.log("buildTree - 添加项目:", item);
                                    result.push(item);

                                    // 如果展开，递归添加子目录
                                    if (item.expanded && item.hasChildren) {
                                        console.log("buildTree - 递归展开:", contents[i]);
                                        buildTree(contents[i], level + 1, expandedItems);
                                    }
                                }
                            }

                            // 展开状态存储
                            if (!expandedItems) {
                                expandedItems = {};
                                console.log("buildTree - 初始化展开状态存储");
                            }

                            // 从根目录开始构建
                            buildTree(fileSystemModel.currentPath, 0, expandedItems);
                            console.log("buildTree - 构建完成，结果数量:", result.length, "结果:", result);
                            return result;
                        }
                        spacing: 1

                        delegate: Rectangle {
                            width: directoryList.width
                            height: 30
                            color: selectedFolderId === modelData.id ? "#e3f2fd" : "transparent"
                            border.color: selectedFolderId === modelData.id ? "#2196f3" : "transparent"
                            border.width: 1

                            RowLayout {
                                anchors.fill: parent
                                anchors.margins: 5
                                spacing: 5

                                // 缩进
                                Item {
                                    width: modelData.level * 20
                                    height: 1
                                }

                                // 展开/折叠按钮
                                Button {
                                    id: expandButton
                                    width: 16
                                    height: 16
                                    // ▶⋁▸▾ⅴ∨
                                    text: modelData.hasChildren ? (modelData.expanded ? "▾" : "▸") : "  "
                                    font.pixelSize: 16
                                    background: Rectangle {
                                        color: "transparent"
                                        border.width: 0
                                    }
                                    //visible: modelData.hasChildren
                                    onClicked: {
                                        console.log("expandButton - 点击展开/折叠按钮:", modelData.id);
                                        console.log("expandButton - 当前展开状态:", modelData.expanded);
                                        console.log("expandButton - 当前是否有子目录:", modelData.hasChildren);
                                        console.log("expandButton - 展开状态存储:", expandedItems[modelData.id]);

                                        // 切换展开状态
                                        var newExpandedState = !modelData.expanded;
                                        expandedItems[modelData.id] = newExpandedState;
                                        console.log("expandButton - 设置新展开状态:", newExpandedState);

                                        // 强制刷新列表 - 通过修改 expandedItems 来触发重建
                                        expandedItems = expandedItems;
                                        console.log("expandButton - 列表已刷新");
                                        fileSystemModel.refresh();
                                    }
                                }

                                // 文件夹图标容器
                                FileObjectItem {
                                    width: 20
                                    height: 20
                                    itemId: modelData.id
                                    isDirectory: true
                                    iconSize: 20
                                    statusIconSize: 12
                                    centerIcon: false
                                    fileSystemModelParam: fileSystemModel
                                    systemIconProviderParam: systemIconProvider
                                    refreshTrigger: fileSystemModel.currentPath
                                }

                                // 名称
                                Text {
                                    Layout.fillWidth: true
                                    text: modelData.name
                                    elide: Text.ElideRight
                                    font.pixelSize: 12
                                }

                            }

                            MouseArea {
                                anchors.fill: parent
                                z: -1  // 放在按钮后面
                                onClicked: {
                                    console.log("左侧目录树点击目录:", modelData);
                                    // 判断是否是文件夹
                                    selectedFolderId = modelData.id;

                                    // 点击文件夹时触发syncFolderAndFiles同步文件夹和文件数据
                                    syncFolderAndFilesById(modelData.id);
                                }
                            }
                        }
                    }
                }
            }
        }

        // 右侧面板 - 文件图标视图
        Rectangle {
            Layout.fillHeight: true
            Layout.fillWidth: true
            color: "#ffffff"
            border.color: "#d0d0d0"
            border.width: 1

            ColumnLayout {
                anchors.fill: parent
                anchors.margins: 0
                spacing: 10

                // 窗口工具栏
                WindowToolBar {
                    Layout.fillWidth: true
                    mainWindow: ApplicationWindow.window
                    title: "文件浏览"
                }

                // 标题栏
                RowLayout {
                    Layout.fillWidth: true
                    spacing: 10
                    // anchors.margins 对 RowLayout 不生效，RowLayout 只支持 Layout.margins
                    Layout.leftMargin: 10
                    Layout.rightMargin: 10

                    // 返回按钮
                    Button {
                        text: "←"
                        Layout.preferredWidth: 30
                        enabled: {
                            var currentPath = selectedFolderId;
                            return fileSystemModel.canGoUp(currentPath);
                        }
                        onClicked: {
                            var currentPath = selectedFolderId;
                            var parentPath = fileSystemModel.getParentPath(currentPath);
                            if (parentPath !== "") {
                                selectedFolderId = parentPath;
                                console.log("右侧面板返回上级目录:", parentPath);
                            }
                        }
                    }

                    Item {
                        Layout.fillWidth: true
                    }

                    Text {
                        text: {
                            var currentPath = selectedFolderId;
                            // 尝试获取路径的友好名称
                            var folderName = fileSystemModel.getFolderName(currentPath);
                            return "查看目录: " + (folderName !== currentPath ? folderName : "根目录");
                        }
                        font.pixelSize: 12
                        color: "#666666"
                        elide: Text.ElideLeft
                        Layout.maximumWidth: 300
                    }
                }

                // 文件图标网格
                ScrollView {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    clip: true
                    Layout.margins: 10

                    GridView {
                        id: fileIconGrid
                        model: {
                            var currentPath = selectedFolderId;
                            console.log("gridview--model--change:", currentPath);
                            return fileSystemModel.getDirectoryContents(currentPath, true); // 包含文件
                        }
                        cellWidth: 120
                        cellHeight: 100

                        delegate: Rectangle {
                            width: fileIconGrid.cellWidth - 10
                            height: fileIconGrid.cellHeight - 10
                            color: selectedFolderId === modelData ? "#e3f2fd" : "transparent"
                            border.color: selectedFolderId === modelData ? "#2196f3" : "#e0e0e0"
                            border.width: 1
                            radius: 5

                            ColumnLayout {
                                anchors.fill: parent
                                anchors.margins: 2
                                spacing: 1

                                // 文件图标容器
                                FileObjectItem {
                                    Layout.fillWidth: true
                                    Layout.preferredHeight: 40
                                    itemId: modelData
                                    isDirectory: fileSystemModel ? fileSystemModel.isDirectory(modelData) : false
                                    iconSize: 32
                                    statusIconSize: 16
                                    centerIcon: true
                                    fileSystemModelParam: fileSystemModel
                                    systemIconProviderParam: systemIconProvider
                                    refreshTrigger: fileSystemModel ? fileSystemModel.currentPath : ""
                                }

                                // 文件名
                                Text {
                                    Layout.fillWidth: true
                                    text: fileSystemModel.getFileName(modelData)
                                    elide: Text.ElideMiddle
                                    font.pixelSize: 10
                                    horizontalAlignment: Text.AlignHCenter
                                    wrapMode: Text.NoWrap
                                    maximumLineCount: 1
                                }

                                // 文件大小
                                Text {
                                    Layout.fillWidth: true
                                    text: fileSystemModel.getFileSize(modelData)
                                    font.pixelSize: 8
                                    color: "#666666"
                                    horizontalAlignment: Text.AlignHCenter
                                }

                                 // 操作按钮行（仅对文件显示）：根据状态显示不同按钮
                                 RowLayout {
                                     Layout.fillWidth: true
                                     Layout.alignment: Qt.AlignHCenter
                                     visible: !fileSystemModel.isDirectory(modelData)
                                     spacing: 1

                                     Button {
                                         Layout.preferredWidth: 28
                                         Layout.preferredHeight: 18
                                         text: "下载"
                                         font.pixelSize: 9
                                         visible: {
                                             if (fileSystemModel.isDirectory(modelData)) return false;
                                             var status = fileSystemModel.getFileStatus(modelData);
                                             return (status & 0x00000001) !== 0; // 待下载状态显示下载按钮 (0x0000 0001)
                                         }
                                         enabled: visible
                                         onClicked: downloadFile(modelData)
                                     }

                                     Button {
                                         Layout.preferredWidth: 28
                                         Layout.preferredHeight: 18
                                         text: "提交"
                                         font.pixelSize: 8
                                         visible: {
                                             if (fileSystemModel.isDirectory(modelData)) return false;
                                             var status = fileSystemModel.getFileStatus(modelData);
                                             return (status & 0x00000010) !== 0 || (status & 0x00000100) !== 0; // 待提交变更状态(0x0000 0010)或待提交新增状态(0x0000 0100)显示提交按钮
                                         }
                                         enabled: visible
                                        onClicked: {
                                            console.log("文件提交:", modelData);
                                            // 获取当前文件夹ID
                                            var currentFolderId = selectedFolderId;
                                            // 从文件夹获取对应的网盘ID
                                            var diskId = fileSystemModel.getFolderDiskId(currentFolderId);
                                            if (diskId !== "" && currentFolderId !== "") {
                                                commandExecutor.executeCommitFile(diskId, currentFolderId, modelData);
                                            } else {
                                                console.log("无法获取网盘ID或文件夹ID，跳过文件提交");
                                            }
                                        }
                                     }
                                     Button {
                                         Layout.preferredWidth: 28
                                         Layout.preferredHeight: 18
                                         text: "撤回"
                                         font.pixelSize: 8
                                         visible: {
                                             if (fileSystemModel.isDirectory(modelData)) return false;
                                             var status = fileSystemModel.getFileStatus(modelData);
                                             return (status & 0x00000010) !== 0; // 待提交变更状态显示撤回按钮 (0x0000 0010)
                                         }
                                         enabled: visible
                                        onClicked: {
                                            console.log("文件撤回:", modelData);
                                            // 通过 CommandExecutor 调用回撤方法
                                            commandExecutor.executeRollbackFile(modelData);
                                        }
                                     }
                                 }
                            }

                            MouseArea {
                                anchors.fill: parent
                                acceptedButtons: Qt.LeftButton | Qt.RightButton
                                z: -1

                                onDoubleClicked: mouse => {
                                    if (mouse.button === Qt.LeftButton && fileSystemModel.isDirectory(modelData)) {
                                        // 更新右侧面板的当前路径，不影响左侧目录树
                                       console.log("右侧面板进入目录:", modelData);
                                        selectedFolderId = modelData;

                                        // 进入文件夹时触发syncFolderAndFiles同步文件夹和文件数据
                                        syncFolderAndFilesById(modelData);
                                    } else if (mouse.button === Qt.LeftButton) {
                                        // 双击文件：打开
                                        if (!fileSystemModel.isDirectory(modelData)) {
                                            openFile(modelData);
                                        }
                                    }
                                }

                                onClicked: mouse => {
                                    if (mouse.button === Qt.RightButton) {
                                        contextMenu.popup();
                                    }
                                }

                                onPressAndHold: mouse => {
                                    if (mouse.source === Qt.MouseEventNotSynthesized) {
                                        contextMenu.popup();
                                    }
                                }
                            }

                            // 右键菜单
                            Menu {
                                id: contextMenu

                                // 文件菜单项
                                MenuItem {
                                    text: "打开"
                                    visible: !fileSystemModel.isDirectory(modelData)
                                    height: visible ? implicitHeight : 0
                                    onTriggered: {
                                        openFile(modelData);
                                    }
                                }

                                MenuItem {
                                    text: "下载"
                                    visible: {
                                        if (fileSystemModel.isDirectory(modelData)) return false;
                                        var status = fileSystemModel.getFileStatus(modelData);
                                        return (status & 0x00000001) !== 0; // 待下载状态 (0x0000 0001)
                                    }
                                    height: visible ? implicitHeight : 0
                                    onTriggered: {
                                        downloadFile(modelData);
                                    }
                                }

                                MenuItem {
                                    text: "提交"
                                    visible: {
                                        if (fileSystemModel.isDirectory(modelData)) return false;
                                        var status = fileSystemModel.getFileStatus(modelData);
                                        return (status & 0x00000010) !== 0 || (status & 0x00000100) !== 0; // 待提交变更状态(0x0000 0010)或待提交新增状态(0x0000 0100)
                                    }
                                    height: visible ? implicitHeight : 0
                                    onTriggered: {
                                        console.log("文件提交:", modelData);
                                        var currentFolderId = selectedFolderId;
                                        var diskId = fileSystemModel.getFolderDiskId(currentFolderId);
                                        if (diskId !== "" && currentFolderId !== "") {
                                            commandExecutor.executeCommitFile(diskId, currentFolderId, modelData);
                                        } else {
                                            console.log("无法获取网盘ID或文件夹ID，跳过文件提交");
                                        }
                                    }
                                }

                                MenuItem {
                                    text: "撤回"
                                    visible: {
                                        if (fileSystemModel.isDirectory(modelData)) return false;
                                        var status = fileSystemModel.getFileStatus(modelData);
                                        return (status & 0x00000010) !== 0; // 待提交变更状态 (0x0000 0010)
                                    }
                                    height: visible ? implicitHeight : 0
                                    onTriggered: {
                                        console.log("文件撤回:", modelData);
                                        // 通过 CommandExecutor 调用回撤方法
                                        commandExecutor.executeRollbackFile(modelData);
                                    }
                                }

                                MenuSeparator {
                                    visible: !fileSystemModel.isDirectory(modelData)
                                    height: visible ? implicitHeight : 0
                                }

                                // 文件夹菜单项
                                MenuItem {
                                    text: "打开"
                                    visible: fileSystemModel.isDirectory(modelData)
                                    height: visible ? implicitHeight : 0
                                    onTriggered: {
                                        console.log("右侧面板进入目录:", modelData);
                                        selectedFolderId = modelData;
                                        syncFolderAndFilesById(modelData);
                                    }
                                }

                                MenuSeparator {
                                    visible: fileSystemModel.isDirectory(modelData)
                                    height: visible ? implicitHeight : 0
                                }

                                // 通用菜单项
                                MenuItem {
                                    text: "删除"
                                    onTriggered: {
                                        console.log("删除项:", modelData);
                                        // 保存待删除的项ID
                                        pendingDeleteItemId = modelData;
                                        // 显示删除确认对话框
                                        deleteConfirmDialog.open();
                                    }
                                }

                                MenuItem {
                                    text: "重命名"
                                    onTriggered: {
                                        console.log("重命名项:", modelData);
                                        // 保存待重命名的项ID
                                        pendingRenameItemId = modelData;
                                        // 打开重命名对话框
                                        renameDialog.open();
                                    }
                                }

                                MenuItem {
                                    text: "属性"
                                    onTriggered: {
                                        console.log("查看属性:", modelData);
                                        // 设置当前查看的项ID
                                        propertyDialogItemId = modelData;
                                        // 打开属性对话框
                                        propertyDialog.open();
                                    }
                                }
                            }
                        }
                    }
                }

                // 底部操作栏
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 50
                    Layout.maximumHeight: 50
                    color: "#f5f5f5"
                    border.color: "#d0d0d0"
                    border.width: 1
                    Layout.topMargin: 5

                    RowLayout {
                        anchors.fill: parent
                        anchors.margins: 10
                        spacing: 10

                        Item {
                            Layout.fillWidth: true
                        }

                        Button {
                            text: "添加文件"
                            Layout.preferredWidth: 100
                            Layout.preferredHeight: 35
                            onClicked: {
                                console.log("上传文件按钮被点击");
                                console.log("selectedFolderId", selectedFolderId);
                                // 获取当前路径（currentPath）作为文件夹ID
                                var currentFolderId = selectedFolderId;
                                console.log("当前路径（currentdPath）值:", currentFolderId);
                                // 调用文件选择并插入上传命令，folder_id 将设置为当前 currentPath 值
                                backendService.selectAndAddFile(currentFolderId);
                            }
                        }
                    }
                }
            }
        }
    }


    // 同步指定路径的文件夹和文件数据
    function syncFolderAndFilesById(folderId) {
        console.log("准备同步文件夹和文件数据，文件夹ID:", folderId);

        // 从文件夹获取对应的网盘ID
        var diskId = fileSystemModel.getFolderDiskId(folderId);
        if (diskId === "") {
            console.log("无法获取文件夹的网盘ID，跳过文件夹和文件同步");
            return;
        }

        console.log("开始同步文件夹，网盘ID:", folderId);
        commandExecutor.executeSyncFolders(folderId);

        console.log("开始同步文件，文件夹ID:", folderId);
        commandExecutor.executeSyncFiles(folderId);
    }

    // 打开文件：先检查是否已下载，如果已下载则直接打开，否则先下载再打开
    function openFile(fileId) {
        console.log("准备打开文件，文件ID:", fileId);
        
        if (fileSystemModel.isDirectory(fileId)) {
            console.log("目标是文件夹，跳过打开动作:", fileId);
            return;
        }
        
        // 检查文件状态
        var status = fileSystemModel.getFileStatus(fileId);
        console.log("文件状态:", status, "文件ID:", fileId);
        
        // 状态 0 表示已同步（已下载），状态 1 表示待下载
        if ((status & 0x00000001) !== 0) {
            // 文件待下载，先下载再打开
            console.log("文件未下载，先下载再打开，文件ID:", fileId);
            // 设置待打开的文件ID，下载完成后会自动打开
            pendingOpenFileId = fileId;
            // 直接调用下载命令，不通过 downloadFile 函数（避免清除 pendingOpenFileId）
            var fileName = fileSystemModel.getFileName(fileId);
            commandExecutor.executeDownloadFile("", fileName, fileId);
        } else {
            // 文件已下载，直接打开
            console.log("文件已下载，直接打开，文件ID:", fileId);
            openLocalFile(fileId);
        }
    }

    // 打开本地文件
    function openLocalFile(fileId) {
        console.log("准备打开本地文件，文件ID:", fileId);

        var workBase = backendService.getUserWorkBaseDir();
        var fullPath;

        // 优先使用 localFilePath 字段
        var localFilePath = fileSystemModel.getLocalFilePath(fileId);
        if (localFilePath !== "") {
            fullPath = workBase + "/" + localFilePath;
            console.log("使用 localFilePath 字段，完整路径:", fullPath);
        } else {
            // 回退到根据文件夹路径和文件名构建
            var fileName = fileSystemModel.getFileName(fileId);
            var folderPath = fileSystemModel.getFileFolderPath(fileId);

            if (fileName === "" || fileName === fileId) {
                console.log("无法获取文件名，文件ID:", fileId);
                return;
            }

            // 构建本地文件路径
            if (folderPath !== "") {
                // 清理路径：移除开头的斜杠
                var cleanFolderPath = folderPath;
                if (cleanFolderPath.startsWith('/')) {
                    cleanFolderPath = cleanFolderPath.substring(1);
                }
                fullPath = workBase + "/" + cleanFolderPath + "/" + fileName;
            } else {
                // 如果没有文件夹路径，只使用文件名
                fullPath = workBase + "/" + fileName;
            }
            console.log("使用文件夹路径和文件名构建，完整路径:", fullPath);
        }

        backendService.openFile(fullPath);
    }

    // 下载文件（仅下载，不打开）
    function downloadFile(fileId) {
        console.log("下载文件请求，文件ID:", fileId);
        if (fileSystemModel.isDirectory(fileId)) {
            console.log("目标是文件夹，跳过下载动作:", fileId);
            return;
        }
        // 清除待打开文件ID，确保纯下载操作不会触发打开
        pendingOpenFileId = "";
        var fileName = fileSystemModel.getFileName(fileId);
        // 注意：URL字段已移除，直接使用文件ID进行下载
        console.log("开始下载文件，文件ID:", fileId, "文件名:", fileName);
        commandExecutor.executeDownloadFile("", fileName, fileId);
    }


    // 连接同步文件夹和文件完成信号
    Connections {
        target: commandExecutor
        function onSyncFoldersCompleted(resultCode, message) {
            console.log("文件夹同步完成，结果码:", resultCode, "消息:", message);
            if (resultCode === 0) {
                console.log("文件夹同步成功，刷新左侧目录树");
                // 刷新文件系统模型
                fileSystemModel.refresh();
                // 强制刷新左侧目录树 - 通过修改 expandedItems 来触发重建
                expandedItems = expandedItems;
            } else {
                console.log("文件夹同步失败:", message);
            }
        }

        function onSyncFilesCompleted(resultCode, message) {
            console.log("文件同步完成，结果码:", resultCode, "消息:", message);
            if (resultCode === 0) {
                console.log("文件同步成功，刷新文件图标视图");
                // 触发文件图标视图刷新
                fileIconGrid.model = Qt.binding(function() {
                    var currentPath = selectedFolderId;
                    return fileSystemModel.getDirectoryContents(currentPath, true); // 包含文件
                });
            } else {
                console.log("文件同步失败:", message);
            }
        }

        function onDownloadFileCompleted(resultCode, message, filePath) {
            console.log("文件下载完成，结果码:", resultCode, "消息:", message);
            if (resultCode === 0) {
                console.log("文件下载成功，保存路径:", filePath);

                // 如果有待打开的文件，自动打开
                if (pendingOpenFileId !== "") {
                    console.log("自动打开下载完成的文件:", pendingOpenFileId);
                    openLocalFile(pendingOpenFileId);

                    // 后端已在下载完成时更新状态为1，这里不再重复更新
                    pendingOpenFileId = ""; // 清除待打开文件ID
                }
            } else {
                console.log("文件下载失败:", message);
                pendingOpenFileId = ""; // 清除待打开文件ID
            }
        }

        function onDownloadProgress(bytesReceived, bytesTotal) {
            if (bytesTotal > 0) {
                var progress = (bytesReceived / bytesTotal * 100).toFixed(1);
                console.log("下载进度:", progress + "%");
                // 这里可以显示下载进度
            }
        }

         function onOpenFileCompleted(resultCode, message) {
             console.log("文件打开完成，结果码:", resultCode, "消息:", message);
             if (resultCode === 0) {
                 console.log("文件打开成功");
                 // 清除待打开文件ID
                 pendingOpenFileId = "";
             } else {
                 console.log("文件打开失败:", message);
                 // 注意：打开失败时不再自动触发下载，因为 openFile 函数已经处理了下载逻辑
                 // 清除待打开文件ID
                 pendingOpenFileId = "";
             }
         }

         function onCommitFileCompleted(resultCode, message) {
             console.log("文件提交完成，结果码:", resultCode, "消息:", message);
             if (resultCode === 0) {
                 console.log("文件提交成功:", message);
                 // 文件提交成功后，刷新文件图标视图
                 console.log("文件提交成功，刷新文件图标视图");
                 if (fileIconGrid) {
                     // 先清空，再下一帧重建，强制重建委托
                     fileIconGrid.model = [];
                     Qt.callLater(function() {
                         var currentPath = selectedFolderId;
                         fileIconGrid.model = fileSystemModel.getDirectoryContents(currentPath, true);
                     });
                 }
                 // 这里可以显示提交成功的提示
             } else {
                 console.log("文件提交失败:", message);
                 // 这里可以显示提交失败的提示
             }
         }

         function onRollbackFileCompleted(resultCode, message) {
             console.log("文件撤回完成，结果码:", resultCode, "消息:", message);
             if (resultCode === 0) {
                 console.log("文件撤回成功:", message);
                 // 文件撤回成功后，刷新文件图标视图
                 console.log("文件撤回成功，刷新文件图标视图");
                 if (fileIconGrid) {
                     // 先清空，再下一帧重建，强制重建委托
                     fileIconGrid.model = [];
                     Qt.callLater(function() {
                         var currentPath = selectedFolderId;
                         fileIconGrid.model = fileSystemModel.getDirectoryContents(currentPath, true);
                     });
                 }
                 // 这里可以显示撤回成功的提示
             } else {
                 console.log("文件撤回失败:", message);
                 // 这里可以显示撤回失败的提示
             }
         }
    }

    // 当数据库文件发生变更（下载、编辑等）时，刷新图标视图
    Connections {
        target: databaseManager
        function onFilesChanged() {
            console.log("检测到数据库文件变更，刷新文件图标视图");
            if (fileIconGrid) {
                // 先清空，再下一帧重建，强制重建委托
                fileIconGrid.model = [];
                Qt.callLater(function() {
                    var currentPath = selectedFolderId;
                    fileIconGrid.model = fileSystemModel.getDirectoryContents(currentPath, true);
                });
            }
        }
    }

    Connections {
        target: fileSystemModel
        function onFilesChanged() {
            // 文件系统变更后，刷新右侧文件图标视图
            console.log("文件系统变更后，刷新右侧文件图标视图");
            if (fileIconGrid) {
                // 先清空，再下一帧重建，强制重建委托
                fileIconGrid.model = [];
                Qt.callLater(function() {
                    var currentPath = selectedFolderId;
                    fileIconGrid.model = fileSystemModel.getDirectoryContents(currentPath, true);
                });
            }
        }
    }

    // 文件属性对话框
    property string propertyDialogItemId: ""

    Dialog {
        id: propertyDialog
        title: fileSystemModel.isDirectory(propertyDialogItemId) ? "文件夹属性" : "文件属性"
        anchors.centerIn: parent
        width: 500
        height: 400
        modal: true
        
        background: Rectangle {
            color: "#ffffff"
            border.color: "#d0d0d0"
            border.width: 1
            radius: 4
        }
        
        contentItem: ScrollView {
            clip: true
            ColumnLayout {
                spacing: 15
                anchors.margins: 20
                width: propertyDialog.width - 40

                // 标题
                Text {
                    text: fileSystemModel.isDirectory(propertyDialogItemId) ? "文件夹属性" : "文件属性"
                    font.pixelSize: 16
                    font.bold: true
                    color: "#333333"
                    Layout.fillWidth: true
                    Layout.bottomMargin: 10
                }

                // 分隔线
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 1
                    color: "#e0e0e0"
                    Layout.bottomMargin: 10
                }

                // 名称
                RowLayout {
                    Layout.fillWidth: true
                    spacing: 10
                    
                    Text {
                        text: "名称:"
                        font.pixelSize: 12
                        color: "#666666"
                        Layout.preferredWidth: 100
                    }
                    
                    Text {
                        Layout.fillWidth: true
                        text: fileSystemModel.isDirectory(propertyDialogItemId) 
                              ? fileSystemModel.getFolderName(propertyDialogItemId)
                              : fileSystemModel.getFileName(propertyDialogItemId)
                        font.pixelSize: 12
                        color: "#333333"
                        elide: Text.ElideMiddle
                    }
                }

                // 类型
                RowLayout {
                    Layout.fillWidth: true
                    spacing: 10
                    
                    Text {
                        text: "类型:"
                        font.pixelSize: 12
                        color: "#666666"
                        Layout.preferredWidth: 100
                    }
                    
                    Text {
                        Layout.fillWidth: true
                        text: fileSystemModel.isDirectory(propertyDialogItemId) 
                              ? "文件夹"
                              : fileSystemModel.getFileType(propertyDialogItemId)
                        font.pixelSize: 12
                        color: "#333333"
                    }
                }

                // 大小
                RowLayout {
                    Layout.fillWidth: true
                    spacing: 10
                    visible: !fileSystemModel.isDirectory(propertyDialogItemId)
                    
                    Text {
                        text: "大小:"
                        font.pixelSize: 12
                        color: "#666666"
                        Layout.preferredWidth: 100
                    }
                    
                    Text {
                        Layout.fillWidth: true
                        text: fileSystemModel.getFileSize(propertyDialogItemId)
                        font.pixelSize: 12
                        color: "#333333"
                    }
                }

                // 本地文件大小（仅文件）
                RowLayout {
                    Layout.fillWidth: true
                    spacing: 10
                    visible: !fileSystemModel.isDirectory(propertyDialogItemId) && fileSystemModel.getLocalFileSize(propertyDialogItemId) > 0
                    
                    Text {
                        text: "本地大小:"
                        font.pixelSize: 12
                        color: "#666666"
                        Layout.preferredWidth: 100
                    }
                    
                    Text {
                        Layout.fillWidth: true
                        text: {
                            var size = fileSystemModel.getLocalFileSize(propertyDialogItemId);
                            if (size < 1024) {
                                return size + " B";
                            } else if (size < 1024 * 1024) {
                                return (size / 1024).toFixed(2) + " KB";
                            } else if (size < 1024 * 1024 * 1024) {
                                return (size / (1024 * 1024)).toFixed(2) + " MB";
                            } else {
                                return (size / (1024 * 1024 * 1024)).toFixed(2) + " GB";
                            }
                        }
                        font.pixelSize: 12
                        color: "#333333"
                    }
                }

                // 状态
                RowLayout {
                    Layout.fillWidth: true
                    spacing: 10
                    
                    Text {
                        text: "状态:"
                        font.pixelSize: 12
                        color: "#666666"
                        Layout.preferredWidth: 100
                    }
                    
                    Text {
                        Layout.fillWidth: true
                        text: {
                            var status = fileSystemModel.isDirectory(propertyDialogItemId)
                                         ? fileSystemModel.getFolderStatus(propertyDialogItemId)
                                         : fileSystemModel.getFileStatus(propertyDialogItemId);
                            switch (status) {
                            case -1:
                                return "已删除";
                            case 0:
                                return "未同步";
                            case 1:
                                return "已同步";
                            case 2:
                                return "已修改";
                            default:
                                return "未知";
                            }
                        }
                        font.pixelSize: 12
                        color: "#333333"
                    }
                }

                // 本地文件路径（仅文件，且存在时显示）
                RowLayout {
                    Layout.fillWidth: true
                    spacing: 10
                    visible: !fileSystemModel.isDirectory(propertyDialogItemId) && fileSystemModel.getLocalFilePath(propertyDialogItemId) !== ""
                    
                    Text {
                        text: "本地路径:"
                        font.pixelSize: 12
                        color: "#666666"
                        Layout.preferredWidth: 100
                    }
                    
                    Text {
                        Layout.fillWidth: true
                        text: {
                            var workBase = backendService.getUserWorkBaseDir();
                            var localPath = fileSystemModel.getLocalFilePath(propertyDialogItemId);
                            return workBase + "/" + localPath;
                        }
                        font.pixelSize: 12
                        color: "#333333"
                        elide: Text.ElideMiddle
                        wrapMode: Text.Wrap
                    }
                }

                // 本地文件校验和（仅文件，且存在时显示）
                RowLayout {
                    Layout.fillWidth: true
                    spacing: 10
                    visible: !fileSystemModel.isDirectory(propertyDialogItemId) && fileSystemModel.getLocalFileChecksum(propertyDialogItemId) !== ""
                    
                    Text {
                        text: "本地校验和:"
                        font.pixelSize: 12
                        color: "#666666"
                        Layout.preferredWidth: 100
                    }
                    
                    Text {
                        Layout.fillWidth: true
                        text: fileSystemModel.getLocalFileChecksum(propertyDialogItemId)
                        font.pixelSize: 12
                        color: "#333333"
                        elide: Text.ElideMiddle
                        font.family: "Courier"
                    }
                }

                // 文件夹类型（仅文件夹）
                RowLayout {
                    Layout.fillWidth: true
                    spacing: 10
                    visible: fileSystemModel.isDirectory(propertyDialogItemId)
                    
                    Text {
                        text: "文件夹类型:"
                        font.pixelSize: 12
                        color: "#666666"
                        Layout.preferredWidth: 100
                    }
                    
                    Text {
                        Layout.fillWidth: true
                        text: {
                            var folderType = fileSystemModel.getFolderType(propertyDialogItemId);
                            switch (folderType) {
                            case 1:
                                return "普通文件夹";
                            case 2:
                                return "根文件夹";
                            default:
                                return "未知";
                            }
                        }
                        font.pixelSize: 12
                        color: "#333333"
                    }
                }

                // 分隔线
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 1
                    color: "#e0e0e0"
                    Layout.topMargin: 10
                    Layout.bottomMargin: 10
                }

                // 确定按钮
                RowLayout {
                    Layout.fillWidth: true
                    Layout.alignment: Qt.AlignHCenter
                    spacing: 10
                    
                    Button {
                        text: "确定"
                        Layout.preferredWidth: 80
                        onClicked: {
                            propertyDialog.close();
                            propertyDialogItemId = "";
                        }
                    }
                }
            }
        }
    }

    // 文件覆盖确认对话框
    property string pendingSourceFilePath: ""
    property string pendingTargetFilePath: ""
    property string pendingFileName: ""
    
    // 删除确认对话框
    property string pendingDeleteItemId: ""
    
    // 重命名对话框
    property string pendingRenameItemId: ""

    Dialog {
        id: fileOverwriteDialog
        title: "文件已存在"
        anchors.centerIn: parent
        width: 400
        modal: true
        
        background: Rectangle {
            color: "#ffffff"
            border.color: "#d0d0d0"
            border.width: 1
            radius: 4
        }
        
        contentItem: ColumnLayout {
            spacing: 20
            anchors.margins: 20

            Text {
                text: "目标文件已存在：\n" + pendingFileName + "\n\n是否覆盖？"
                font.pixelSize: 14
                color: "#333333"
                Layout.fillWidth: true
                Layout.alignment: Qt.AlignHCenter
                wrapMode: Text.WordWrap
            }
            
            RowLayout {
                Layout.fillWidth: true
                Layout.alignment: Qt.AlignHCenter
                spacing: 10
                
                Button {
                    text: "覆盖"
                    Layout.preferredWidth: 80
                    onClicked: {
                        console.log("用户选择覆盖文件");
                        fileOverwriteDialog.close();
                        // 调用后端方法处理覆盖确认
                        backendService.handleFileOverwriteConfirm(true, pendingSourceFilePath, pendingTargetFilePath, selectedFolderId);
                        // 清除待处理信息
                        pendingSourceFilePath = "";
                        pendingTargetFilePath = "";
                        pendingFileName = "";
                    }
                }
                
                Button {
                    text: "取消"
                    Layout.preferredWidth: 80
                    onClicked: {
                        console.log("用户选择取消覆盖");
                        fileOverwriteDialog.close();
                        // 调用后端方法处理取消
                        backendService.handleFileOverwriteConfirm(false, pendingSourceFilePath, pendingTargetFilePath, selectedFolderId);
                        // 清除待处理信息
                        pendingSourceFilePath = "";
                        pendingTargetFilePath = "";
                        pendingFileName = "";
                    }
                }
            }
        }
    }

    // 连接文件覆盖确认信号
    Connections {
        target: backendService
        function onAskFileOverwrite(sourceFilePath, targetFilePath, fileName) {
            console.log("收到文件覆盖确认请求，源文件:", sourceFilePath, "目标文件:", targetFilePath, "文件名:", fileName);
            // 保存待处理信息
            pendingSourceFilePath = sourceFilePath;
            pendingTargetFilePath = targetFilePath;
            pendingFileName = fileName;
            // 显示确认对话框
            fileOverwriteDialog.open();
        }
    }

    // 删除确认对话框
    Dialog {
        id: deleteConfirmDialog
        title: "确认删除"
        anchors.centerIn: parent
        width: 400
        modal: true
        
        background: Rectangle {
            color: "#ffffff"
            border.color: "#d0d0d0"
            border.width: 1
            radius: 4
        }
        
        contentItem: ColumnLayout {
            spacing: 20
            anchors.margins: 20

            Text {
                id: deleteConfirmText
                text: {
                    if (pendingDeleteItemId === "") return "确定要删除吗？";
                    var isDir = fileSystemModel.isDirectory(pendingDeleteItemId);
                    var name = isDir 
                        ? fileSystemModel.getFolderName(pendingDeleteItemId)
                        : fileSystemModel.getFileName(pendingDeleteItemId);
                    return "确定要删除" + (isDir ? "文件夹" : "文件") + "吗？\n\n" + name;
                }
                font.pixelSize: 14
                color: "#333333"
                Layout.fillWidth: true
                Layout.alignment: Qt.AlignHCenter
                wrapMode: Text.WordWrap
            }
            
            RowLayout {
                Layout.fillWidth: true
                Layout.alignment: Qt.AlignHCenter
                spacing: 10
                
                Button {
                    text: "确定"
                    Layout.preferredWidth: 80
                    onClicked: {
                        console.log("用户确认删除，项ID:", pendingDeleteItemId);
                        if (pendingDeleteItemId !== "") {
                            // 判断是文件还是文件夹，调用不同的删除接口
                            var isDir = fileSystemModel.isDirectory(pendingDeleteItemId);
                            if (isDir) {
                                console.log("删除文件夹:", pendingDeleteItemId);
                                backendService.deleteFolder(pendingDeleteItemId);
                            } else {
                                console.log("删除文件:", pendingDeleteItemId);
                                // 通过 CommandExecutor 调用删除文件方法
                                commandExecutor.executeDeleteFile(pendingDeleteItemId);
                            }
                        }
                        deleteConfirmDialog.close();
                        // 注意：不清除 pendingDeleteItemId，因为删除成功后需要用它来刷新列表
                    }
                }
                
                Button {
                    text: "取消"
                    Layout.preferredWidth: 80
                    onClicked: {
                        console.log("用户取消删除");
                        deleteConfirmDialog.close();
                        pendingDeleteItemId = "";
                    }
                }
            }
        }
    }

    // 重命名对话框
    Dialog {
        id: renameDialog
        title: {
            if (pendingRenameItemId !== "") {
                var isDir = fileSystemModel.isDirectory(pendingRenameItemId);
                return isDir ? "重命名文件夹" : "重命名文件";
            }
            return "重命名";
        }
        anchors.centerIn: parent
        width: 400
        modal: true
        
        background: Rectangle {
            color: "#ffffff"
            border.color: "#d0d0d0"
            border.width: 1
            radius: 4
        }
        
        onOpened: {
            // 对话框打开时，自动填充当前名称并选中
            if (pendingRenameItemId !== "") {
                var currentName = fileSystemModel.getFileName(pendingRenameItemId);
                renameInput.text = currentName;
                var isDir = fileSystemModel.isDirectory(pendingRenameItemId);
                if (isDir) {
                    // 文件夹：全选
                    renameInput.selectAll();
                } else {
                    // 文件：选中文件名（不含扩展名）
                    var lastDotIndex = currentName.lastIndexOf('.');
                    if (lastDotIndex > 0) {
                        renameInput.select(0, lastDotIndex);
                    } else {
                        renameInput.selectAll();
                    }
                }
                renameInput.forceActiveFocus();
            }
        }
        
        onClosed: {
            // 对话框关闭时，如果不是确认操作，则清除待重命名项ID
            if (pendingRenameItemId !== "" && renameInput.text.trim() === "") {
                pendingRenameItemId = "";
            }
        }
        
        contentItem: ColumnLayout {
            spacing: 20
            anchors.margins: 20

            Text {
                text: {
                    if (pendingRenameItemId !== "") {
                        var isDir = fileSystemModel.isDirectory(pendingRenameItemId);
                        return isDir ? "请输入新文件夹名：" : "请输入新文件名：";
                    }
                    return "请输入新名称：";
                }
                font.pixelSize: 14
                color: "#333333"
                Layout.fillWidth: true
            }
            
            TextField {
                id: renameInput
                Layout.fillWidth: true
                placeholderText: "文件名"
                selectByMouse: true
                onAccepted: {
                    // 按回车键时确认重命名
                    if (renameInput.text.trim() !== "") {
                        renameDialog.confirmRename();
                    }
                }
            }
            
            RowLayout {
                Layout.fillWidth: true
                Layout.alignment: Qt.AlignHCenter
                spacing: 10
                
                Button {
                    text: "确定"
                    Layout.preferredWidth: 80
                    onClicked: {
                        renameDialog.confirmRename();
                    }
                }
                
                Button {
                    text: "取消"
                    Layout.preferredWidth: 80
                    onClicked: {
                        console.log("用户取消重命名");
                        renameInput.text = "";
                        renameDialog.close();
                        pendingRenameItemId = "";
                    }
                }
            }
        }
        
        function confirmRename() {
            var newName = renameInput.text.trim();
            if (newName === "") {
                console.log("新名称为空，取消重命名");
                return;
            }
            
            if (pendingRenameItemId !== "") {
                var currentName = fileSystemModel.getFileName(pendingRenameItemId);
                if (newName === currentName) {
                    console.log("新名称与当前名称相同，取消重命名");
                    renameInput.text = "";
                    renameDialog.close();
                    pendingRenameItemId = "";
                    return;
                }
                
                var isDir = fileSystemModel.isDirectory(pendingRenameItemId);
                if (isDir) {
                    console.log("用户确认重命名文件夹，文件夹ID:", pendingRenameItemId, "新文件夹名:", newName);
                    backendService.renameFolder(pendingRenameItemId, newName);
                } else {
                    console.log("用户确认重命名文件，文件ID:", pendingRenameItemId, "新文件名:", newName);
                    backendService.renameFile(pendingRenameItemId, newName);
                }
            }
            renameInput.text = "";
            renameDialog.close();
            // 注意：不清除 pendingRenameItemId，因为重命名成功后需要用它来刷新列表
        }
    }

    // 连接删除文件完成信号
    Connections {
        target: backendService
        function onDeleteFileCompleted(resultCode, message) {
            console.log("删除文件完成，结果码:", resultCode, "消息:", message);
            if (resultCode === 0) {
                console.log("删除成功，刷新文件列表");
                // 删除成功后，刷新当前文件夹的文件列表
                if (selectedFolderId !== "") {
                    syncFolderAndFilesById(selectedFolderId);
                }
                // 清除待删除项ID
                pendingDeleteItemId = "";
            } else {
                console.log("删除失败:", message);
                // 删除失败时也清除待删除项ID
                pendingDeleteItemId = "";
            }
        }
    }

    // 连接删除文件夹完成信号
    Connections {
        target: backendService
        function onDeleteFolderCompleted(resultCode, message) {
            console.log("删除文件夹完成，结果码:", resultCode, "消息:", message);
            if (resultCode === 0) {
                console.log("删除成功，刷新文件夹列表");
                // 删除成功后，刷新文件夹列表和文件列表
                if (selectedFolderId !== "") {
                    // 如果删除的是当前选中的文件夹，需要返回到父文件夹
                    if (pendingDeleteItemId === selectedFolderId) {
                        // TODO: 可能需要返回到父文件夹，这里先刷新当前文件夹
                        // 如果当前文件夹被删除，可能需要清空选中状态
                        selectedFolderId = "";
                    }
                    syncFolderAndFilesById(selectedFolderId);
                }
                // 刷新文件夹树（通过重新加载文件系统模型）
                fileSystemModel.refresh();
                // 清除待删除项ID
                pendingDeleteItemId = "";
            } else {
                console.log("删除失败:", message);
                // 删除失败时也清除待删除项ID
                pendingDeleteItemId = "";
            }
        }
    }

    // 连接重命名文件完成信号
    Connections {
        target: backendService
        function onRenameFileCompleted(resultCode, message) {
            console.log("重命名文件完成，结果码:", resultCode, "消息:", message);
            if (resultCode === 0) {
                console.log("重命名成功，刷新文件列表");
                // 刷新文件夹树（通过重新加载文件系统模型）
                fileSystemModel.refresh();
                // 刷新右侧面板的文件图标视图
                console.log("重命名成功，刷新文件图标视图");
                if (fileIconGrid) {
                    // 先清空，再下一帧重建，强制重建委托
                    fileIconGrid.model = [];
                    Qt.callLater(function() {
                        var currentPath = selectedFolderId;
                        fileIconGrid.model = fileSystemModel.getDirectoryContents(currentPath, true);
                    });
                }
                // 清除待重命名项ID
                pendingRenameItemId = "";
            } else {
                console.log("重命名失败:", message);
                // 重命名失败时也清除待重命名项ID
                pendingRenameItemId = "";
            }
        }
    }

    // 连接重命名文件夹完成信号
    Connections {
        target: backendService
        function onRenameFolderCompleted(resultCode, message) {
            console.log("重命名文件夹完成，结果码:", resultCode, "消息:", message);
            if (resultCode === 0) {
                console.log("重命名成功，刷新文件夹列表");
                // 刷新文件夹树（通过重新加载文件系统模型）
                fileSystemModel.refresh();
                // 刷新右侧面板的文件图标视图
                console.log("重命名文件夹成功，刷新文件图标视图");
                if (fileIconGrid) {
                    // 先清空，再下一帧重建，强制重建委托
                    fileIconGrid.model = [];
                    Qt.callLater(function() {
                        var currentPath = selectedFolderId;
                        fileIconGrid.model = fileSystemModel.getDirectoryContents(currentPath, true);
                    });
                }
                // 清除待重命名项ID
                pendingRenameItemId = "";
            } else {
                console.log("重命名失败:", message);
                // 重命名失败时也清除待重命名项ID
                pendingRenameItemId = "";
            }
        }
    }

}
